// pages/number/index.js
import {
  list,
  add,
  update,
  remove
} from '../../api/number-select'
 
import Notify from '../../miniprogram_npm/@vant/weapp/notify/notify';
import {
  useToast
} from '../../miniprogram_npm/miniprogram-vc-components/toast/useToast';
import {
  useDialog
} from '../../miniprogram_npm/miniprogram-vc-components/dialog/useDialog';

let toast, dialog;

Page({
  options: {
    pureDataPattern: /^_/
  },
  /**
   * 页面的初始数据
   */
  data: {
    dataSource: [],
    _item: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.initPage(options);
    this.fetchData();
  },
  initPage(opts) {

    const data = JSON.parse(decodeURIComponent(opts.data));
    this.setData({
      _item: data
    })
    wx.setNavigationBarTitle({
      title: data.name + '的可选数据',
    })

  },

  fetchData() {
    list({
      numSettingsIds: this.data._item.id
    }, res => {
      this.setData({
        dataSource: res
      })
    })
  },
 
  add() {
    const arr = [...this.data.dataSource];
      if(this.canAddItem()){
        arr.push({
          numSettingsId: this.data._item.id,
          value: ''
        })
        this.setData({
          dataSource: arr
        })
      }else {
        Notify({
          type: 'warning',
          message: '请先保存或移除上一次添加的内容'
        })
      }
  },
  canAddItem(){
    return this.data.dataSource.every(it=> it.id);
  },
  onChangeValue(event) {
    const {
      dataSource
    } = this.data;
    const index = event.currentTarget.dataset.index,
      value = event.detail;
    dataSource[index].value = value;
    this.setData({
      dataSource
    })
  },
  isEmpty(obj) {
    return !obj.value;
  },
  onSave(event) {
    const index = event.currentTarget.dataset.index,
      {
        dataSource,
      } = this.data,
      item = dataSource[index];

    if (this.isEmpty(item)) {
      toast.init({
        value: "格式不正确"
      }).open();
    } else {

      item.id === undefined ?
        add(item, () => {
          Notify({
            type: 'success',
            message: '已保存'
          });
          this.fetchData();
        }, this.fetchData) : update(item, () => {
          Notify({
            type: 'success',
            message: '已保存'
          });
        })
    }
  },
  onRemove(event) {
    const index = event.currentTarget.dataset.index,
      {
        dataSource,
      } = this.data,
      item = dataSource[index];
    if (item.id === undefined) {
      this.viewRemove(dataSource, index);
    } else {
      const dialogInstance = dialog.init({
        title: "",
        content: "确定要移除此配置吗？",
        icon: "icon-warning",
        showCancel: true,
        mask: true
      }, () => {
        remove(item, () => {
          Notify({
            type: 'success',
            message: '已删除'
          });
          dialogInstance.close();
          this.viewRemove(dataSource, index);
        })
      }, () => dialogInstance.close())
      dialogInstance.open();
    }
  },
  viewRemove(dataSource, index) {
    const d = dataSource.filter((_, i) => {
      return i !== index;
    })
    this.setData({
      dataSource: d
    })
 
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    toast = useToast('#toast', this);
    dialog = useDialog('#dialog', this);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})